package com.ztc.ZtcOrder.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aqgj.User.bean.User;
import com.aqgj.util.JsonWrapper;
import com.aqgj.util.Pager;
import com.aqgj.util.StringUtils;
import com.ztc.ZtcClassesPriceForSale.bean.ZtcClassesPriceForSale;
import com.ztc.ZtcClassesPriceForSale.service.ZtcClassesPriceForSaleManager;
import com.ztc.ZtcCtripData.bean.ZtcCtripData;
import com.ztc.ZtcCtripData.service.ZtcCtripDataManager;
import com.ztc.ZtcOrder.bean.ZtcOrder;
import com.ztc.ZtcOrder.service.ZtcOrderManager;
import com.ztc.ZtcOrderTicket.bean.ZtcOrderTicket;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.service.ZtcTransportManager;
import com.ztc.util.excel.ExcelUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * @author
 */
@Controller
@RequestMapping("ztc_order_action")
public class ZtcOrderAction {
	@Autowired
	private ZtcOrderManager ztcOrderManager;
	@Autowired
	private ZtcClassesPriceForSaleManager ztcClassesPriceForSaleManager;

	@Autowired
	private ZtcCtripDataManager ztcCtripDataManager;

	private static final Logger log = LogManager.getLogger(ZtcOrder.class);

	@Autowired
	private ZtcTransportManager ztcTransportManager;

	/**
	 * 后台退票
	 * @param id
	 * @param refundReason
	 * @return
	 */
	@RequestMapping("cancelOrder")
	@ResponseBody
	public HashMap<String, Object> cancelOrder(@RequestParam String id, String refundReason){
		ztcOrderManager.cancelOrder(id,refundReason);
		return JsonWrapper.successWrapper();
	}


	/**
	 * 搜索订单号
	 * @param orderNumber 订单编号
	 * @return
	 */
	@RequestMapping("searchOrder")
	@ResponseBody
	public HashMap<String, Object> searchOrder(@RequestParam String orderNumber){
		Map orderMap = ztcOrderManager.getZcOrderByOrderNumber(orderNumber);
		if(orderMap.get("id") == null){
			return JsonWrapper.failureWrapper("订单不存在");
		}
		return JsonWrapper.successWrapper(ztcOrderManager.getZcOrderByOrderNumber(orderNumber));
	}

	/**
	 * 后台退款
	 * @param orderNumber 订单编号
	 * @param refundType 退款类型 1 退违约金  2 全款退 3 自定义金额
	 * @param refundFee 退款金额
	 * @return
	 */
	@RequestMapping("addRefund")
	@ResponseBody
	public HashMap<String, Object> addRefund(@RequestParam String orderNumber,@RequestParam int refundType, BigDecimal refundFee){
		ztcOrderManager.cancelOrder(orderNumber,refundType,refundFee);
		return JsonWrapper.successWrapper();
	}


	@RequestMapping("getTicketInfo")
	@ResponseBody
	/**
	 * 生成订单
	 * 
	 * @return
	 */
	public HashMap<String, Object> getTicketInfo(String passengerInfos,String id) throws ParseException {
		//
		log.info("开始添加");
		HashMap<String, Object> wapper = new HashMap<>();
		ZtcClassesPriceForSale priceForSale=new ZtcClassesPriceForSale();
		priceForSale.setId(id);
		ZtcClassesPriceForSale price=ztcClassesPriceForSaleManager.searchInfoEquals(priceForSale).get(0);
		if(price.getStatus()==1){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该区段已停售");
			log.info("该区段已停售");
			return wapper;
		}
		List<ZtcOrderTicket> ztcOrderTickets=new ArrayList<>();
		String result=ztcOrderManager.getTicketInfo(passengerInfos, price, ztcOrderTickets);
		if ("1".equals(result)) {
			wapper.put("success", Boolean.valueOf(true));
			wapper.put("msg", "可以出票");
			wapper.put("tickets", ztcOrderTickets);
			log.info("可以出票");
			return wapper;
		} else if ("01".equals(result)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "成人票数量不足");
			log.info("成人票数量不足");
			return wapper;
		} else if ("02".equals(result)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "儿童票数量不足");
			log.info("儿童票数量不足");
			return wapper;
		} else {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误，下单失败");
			log.info("网络错误，下单失败");
			return wapper;
		}
	}

	@RequestMapping("sign")
	@ResponseBody
	/**
	 * 生成订单
	 * 
	 * @return
	 */
	public HashMap<String, Object> save(String orderInfo,String id,String tickets) throws ParseException {
		//
		log.info("开始添加");
		HashMap<String, Object> wapper = new HashMap<>();
		JSONObject order=JSONObject.parseObject(orderInfo);
		ZtcOrder ztcOrder = new ZtcOrder();
		ztcOrder.setOrderTime(new Date());
		ztcOrder.setType(order.getInteger("type"));
		ztcOrder.setOrderBalance(order.getBigDecimal("orderBalance"));
		ztcOrder.setContactName(order.getString("contactName"));
		ztcOrder.setContactPhone(order.getString("contactPhone"));
		ztcOrder.setFkZtcWalletId(order.getString("ztcWalletId"));
		ztcOrder.setFkZtcClassesPriceForSaleId(id);
		ztcOrder.setStatus(0);
		List<ZtcOrderTicket> ztcOrderTickets=new ArrayList<>();
		generateZtcOrderTicketList(tickets,ztcOrderTickets);
		String result = ztcOrderManager.save(ztcOrder,id,ztcOrderTickets);
		if ("1".equals(result)) {
			wapper.put("success", Boolean.valueOf(true));
			wapper.put("msg", "下单成功");
			log.info("下单成功");
			return wapper;
		} else if ("01".equals(result)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "座位不能卖出，请重新下单");
			log.info("座位不能卖出，请重新下单");
			return wapper;
		} else if("02".equals(result)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该区段已停售");
			log.info("该区段已停售");
			return wapper;
		}else{
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误，下单失败");
			log.info("网络错误，下单失败");
			return wapper;
		}
	}

	private void generateZtcOrderTicketList(String tickets, List<ZtcOrderTicket> ztcOrderTickets) {
		if(tickets==null||"".equals(tickets)){
			return;
		}
		JSONArray orderTicketArray=JSON.parseArray(tickets);
		for(int i=0;i<orderTicketArray.size();i++){
			JSONObject jsonObject=orderTicketArray.getJSONObject(i);
			ZtcOrderTicket ztcOrderTicket=new ZtcOrderTicket();
			ztcOrderTicket.setPassengerName(jsonObject.getString("name"));
			ztcOrderTicket.setPassengerBirthday(jsonObject.getDate("passengerBirthday"));
			ztcOrderTicket.setPassengerCardNumber(jsonObject.getString("passengerCardNumber"));
			ztcOrderTicket.setPassengerCardType(jsonObject.getInteger("passengerCardType"));
			ztcOrderTicket.setPassengerType(jsonObject.getInteger("passengerType"));
			ztcOrderTicket.setPrice(jsonObject.getBigDecimal("price"));
			ztcOrderTicket.setSeatNumber(jsonObject.getInteger("seatNumber"));
			ztcOrderTicket.setSeatType(jsonObject.getInteger("seatType"));
			ztcOrderTickets.add(ztcOrderTicket);
		}
	}


	@RequestMapping("get")
	@ResponseBody
	public HashMap<String, Object> get(String id, HttpServletResponse httpResponse) {
		//
		ZtcOrder ztcOrder = new ZtcOrder();
		ztcOrder.setId(id);
		List<ZtcOrder> lists = ztcOrderManager.searchInfo(ztcOrder);
		HashMap<String, Object> wapper = new HashMap<>();
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", lists);
		return wapper;
	}

	@RequestMapping("cancel")
	@ResponseBody
	/**
	 * 取消订单
	 * 
	 * @return
	 */
	public HashMap<String, Object> cancel(String id, String refundReason) throws ParseException {
		//
		log.info("取消订单");
		HashMap<String, Object> wapper = new HashMap<>();
		String result = ztcOrderManager.cancel(id, refundReason);
		if ("1".equals(result)) {
			wapper.put("success", Boolean.valueOf(true));
			wapper.put("msg", "取消订单成功");
			log.info("取消订单成功");
			return wapper;
		} else if ("2".equals(result)) {
			wapper.put("success", Boolean.valueOf(true));
			wapper.put("msg", "申请退款成功");
			log.info("申请退款成功");
			return wapper;
		} else if ("01".equals(result)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "取消订单失败");
			log.info("取消订单失败");
			return wapper;
		} else if("02".equals(result)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "申请退款失败");
			log.info("申请退款失败");
			return wapper;
		}else{
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "订单已取消，不可再取消");
			log.info("订单已取消，不可再取消");
			return wapper;
		}
	}

    /**
     * 获得当前公司所有订单（直通车）
     * @param session
     * @param pageSize  分页大小
     * @param pageNumber  页码
     * @param orderId    订单编号（搜索）
     * @param departDateStart   出发日期（搜索）
     * @param departDateEnd   出发日期（搜索）
     * @param contactName   联系人（搜索）
     * @param contactPhone  联系电话（搜索）
     * @param startDate  开始时间（搜索）
     * @param endDate    结束时间（搜索）
     * @param orderStatus    订单状态（搜索）
     * @return  	符合条件的所有订单
     */
    @RequestMapping("getList")
    @ResponseBody
    public HashMap<String, Object> getList(HttpSession session,@RequestParam(defaultValue = "10") Integer pageSize,
                                           @RequestParam(defaultValue = "1") Integer pageNumber,String orderId,String startDate,String endDate,String departDateStart,String departDateEnd,String contactName,String contactPhone,String orderStatus) {
        User user=(User)session.getAttribute("userInfo");
        ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
        Pager<Map> ztcOrders=ztcOrderManager.getAllZcOrderByCompanyId(ztcTransport,pageSize,pageNumber,orderId,startDate,endDate,departDateStart,departDateEnd,contactName,contactPhone,orderStatus);
        return JsonWrapper.successPagerWrapper(ztcOrders.getContent(),ztcOrders.getRecordTotal());
    }

    /**
     * 获得当前公司所有订单（充值）
     * @param pageSize  分页大小
     * @param pageNumber  页码
     * @param orderId    订单编号（搜索）
     * @param payType   支付类型（1.余额 2.支付宝 3.微信）（搜索）
     * @param startDate  开始时间（搜索）
     * @param endDate    结束时间（搜索）
     * @return  	符合条件的所有订单
     */
    @RequestMapping("getRechargeList")
    @ResponseBody
    public HashMap<String, Object> getRechargeList(@RequestParam(defaultValue = "10") Integer pageSize,
                                           @RequestParam(defaultValue = "1") Integer pageNumber,String orderId,@RequestParam(defaultValue = "0")Integer payType,String startDate,String endDate) {
        Pager<Map> ztcOrders=ztcOrderManager.getRechargeList(pageSize,pageNumber,orderId,payType,startDate,endDate);
        return JsonWrapper.successPagerWrapper(ztcOrders.getContent(),ztcOrders.getRecordTotal());
    }


	/**
	 * 获得当前公司所有订单（去哪儿）
	 * @param pageSize  分页大小
	 * @param pageNumber  页码
	 * @param orderId    订单编号（搜索）
	 * @param payType   支付类型（1.余额 2.支付宝 3.微信）（搜索）
	 * @param startDate  开始时间（搜索）
	 * @param endDate    结束时间（搜索）
	 * @return  	符合条件的所有订单
	 */
	@RequestMapping("getCtripList")
	@ResponseBody
	public HashMap<String, Object> getCtripList(@RequestParam(defaultValue = "10") Integer pageSize,
												   @RequestParam(defaultValue = "1") Integer pageNumber,String orderId,@RequestParam(defaultValue = "0")Integer payType,String startDate,String endDate) {
		Pager<Map> ztcOrders=ztcOrderManager.getCtripList(pageSize,pageNumber,orderId,payType,startDate,endDate);
		return JsonWrapper.successPagerWrapper(ztcOrders.getContent(),ztcOrders.getRecordTotal());
	}


    /**
     * 获得订单详情
     * @param orderId 订单id
     * @return
     */
	@RequestMapping("getOrderDetail")
	@ResponseBody
	public HashMap<String, Object> getOrderDetail(String orderId) {
		if(StringUtils.isBlank(orderId)){
			return JsonWrapper.failureWrapperMsg("订单参数异常！");
		}
		ZtcOrder ztcOrder=ztcOrderManager.get(orderId);
		if(ztcOrder==null){
            return JsonWrapper.failureWrapperMsg("订单详情获取失败！");
        }
		return ztcOrderManager.getOrderDetail(orderId,ztcOrder.getType(),ztcOrder.getOrderType());
	}

	/**
	 * 根据公司ID获取最新N条订单信息.
	 * @param number 条数(6)
	 * @return
	 */
	@RequestMapping("getUpZtcOrderListByTid")
	@ResponseBody
	public HashMap<String, Object> getUpZtcOrderListByTid(HttpSession session,@RequestParam(defaultValue = "6") Integer number){
		User user=(User)session.getAttribute("userInfo");
		return JsonWrapper.successWrapper(ztcOrderManager.getUpZtcOrderListByTid(user.getTransportId(),number));
	}

	/**
	 * 导出excel，当前页
	 * @param response
	 */
	@RequestMapping("exportExcel")
	public void exportFeedBack(HttpServletResponse response, HttpSession session,@RequestParam(defaultValue ="1") Integer pageNumber, @RequestParam(defaultValue ="10") Integer pageSize,String orderId,String startDate,String endDate,String departDateStart,String departDateEnd,String contactName,String contactPhone,String orderStatus) {
		User user=(User)session.getAttribute("userInfo");
		String	fileName="订单列表"+System.currentTimeMillis() + ".xls";
		String	sheetName="订单详情";
		//标题
		String[] title = new String[]{"订单号", "订单状态", "订单日期", "出发日期", "出发站", "到达站", "订单金额(元)", "总票数", "姓名", "联系电话", "乘客信息", "退票金额"};
		ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
		Pager<Map> ztcOrders=ztcOrderManager.getAllZcOrderByCompanyId(ztcTransport,pageSize,pageNumber,orderId,startDate,endDate,departDateStart,departDateEnd,contactName,contactPhone,orderStatus);
		String[][] values = new String[ztcOrders.getContent().size()][];
		for (int i = 0; i < ztcOrders.getContent().size(); i++) {
			values[i] = new String[title.length];
			//将对象内容转换成string
			Map<String, Object> obj = ztcOrders.getContent().get(i);
			values[i][0] = obj.get("order_number").toString();
			values[i][1] = getStatusByInteger(obj.get("status").toString());
			values[i][2] = obj.get("order_time").toString();
			values[i][3] = obj.get("departure_time").toString();
			values[i][4] = obj.get("start_city").toString();
			values[i][5] = obj.get("end_city").toString();
			values[i][6] = obj.get("order_balance").toString();
			values[i][7] = "成人:"+obj.get("remain_seat_number").toString()+"位,儿童:"+obj.get("remain_child_seat_number").toString()+"位";
			values[i][8] = obj.get("contact_name").toString();
			values[i][9] = obj.get("contact_phone").toString();
			values[i][10] = obj.get("pe").toString();
			values[i][11] = obj.get("refund_balance").toString();
		}
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		ExcelUtil.setResponseHeader(response,fileName,wb);
	}

	/**
	 * 导出excel全部数据
	 * @param response
	 */
	@RequestMapping("exportAllExcel")
	public void exportAllExcel(HttpServletResponse response, HttpSession session,String orderId,String startDate,String endDate,String departDateStart,String departDateEnd,String contactName,String contactPhone,String orderStatus) {
		User user=(User)session.getAttribute("userInfo");
		String	fileName="订单列表"+System.currentTimeMillis() + ".xls";
		String	sheetName="订单详情";
		//标题
		String[] title = new String[]{"订单号", "订单状态", "订单日期", "出发日期", "出发站", "到达站", "订单金额(元)", "总票数", "姓名", "联系电话", "乘客信息", "退票金额"};
		ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
		List<Map> ztcOrders=ztcOrderManager.getAllZcOrderByCompanyId(ztcTransport,orderId,startDate,endDate,departDateStart,departDateEnd,contactName,contactPhone,orderStatus);
		String[][] values = new String[ztcOrders.size()][];
		for (int i = 0; i < ztcOrders.size(); i++) {
			values[i] = new String[title.length];
			//将对象内容转换成string
			Map<String, Object> obj = ztcOrders.get(i);
			values[i][0] = obj.get("order_number").toString();
			values[i][1] = getStatusByInteger(obj.get("status").toString());
			values[i][2] = obj.get("order_time").toString();
			values[i][3] = obj.get("departure_time").toString();
			values[i][4] = obj.get("start_city").toString();
			values[i][5] = obj.get("end_city").toString();
			values[i][6] = obj.get("order_balance").toString();
			values[i][7] = "成人:"+obj.get("remain_seat_number").toString()+"位,儿童:"+obj.get("remain_child_seat_number").toString()+"位";
			values[i][8] = obj.get("contact_name").toString();
			values[i][9] = obj.get("contact_phone").toString();
			values[i][10] = obj.get("pe").toString();
			values[i][11] = obj.get("refund_balance").toString();
		}
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		ExcelUtil.setResponseHeader(response,fileName,wb);
	}

	private String getStatusByInteger(String orderStatus){
		switch (orderStatus){
			case "3":orderStatus="已完成";break;
			case "2":orderStatus="待出行";break;
			case "1":orderStatus="出票中";break;
			case "5":orderStatus="已退款";break;
			case "4":orderStatus="退款中";break;
			case "6":orderStatus="退款失败";break;
			case "0":orderStatus="待支付";break;
		}
		return orderStatus;
	}


	/**
	 * 获取快递订单列表.
	 * @param orderNumber 订单编号（搜索）
	 * @param pageSize    每页条数
	 * @param pageNumber  页码
	 * @param startDate  开始时间（搜索）
	 * @param endDate    结束时间（搜索）
	 * @return
	 */
	@RequestMapping("getExpressZtcOrderList")
	@ResponseBody
	public HashMap<String, Object> getExpressZtcOrderList(@RequestParam(defaultValue = "10") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageNumber,String orderNumber,String startDate,String endDate){
		Pager<Map> pager=ztcOrderManager.getExpressZtcOrderList(pageSize,pageNumber,orderNumber,startDate,endDate);
		return JsonWrapper.successPagerWrapper(pager.getContent(),pager.getRecordTotal());
	}

	/**
	 * 获取快递订单详情.
	 *
	 * @return
	 */
	@RequestMapping("getExpressZtcOrderDetail")
	@ResponseBody
	public HashMap<String, Object> getExpressZtcOrderDetail(String oid){
		return ztcOrderManager.getExpressZtcOrderDetail(oid);
	}
}